package com.hyts.dbmeta.base;

import com.hyts.dbmeta.error.DataBaseMetaError;
import lombok.Getter;
import lombok.Setter;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * project-name:coffice-wizard
 * package-name:com.hyts.dbmeta.handler
 * author:Libo/Alex
 * create-date:2018-11-04 18:16
 * copyright:libo-hyts-github
 * email:libo2dev@aliyun.com
 * description:此类主要用于: 用于数据库链接数据源的操作处理器句柄
 * @author libo
 */
public abstract class AbstractConnectionHandler {


    protected AbstractConnectionConfig connectionConfig;


    protected abstract boolean injectClassLoader();


    /**
     * @param connectionConfig
     */
    public AbstractConnectionHandler(AbstractConnectionConfig connectionConfig) {
        this.connectionConfig = connectionConfig;
    }

    /**
     *
     * @param fullConnectionStr
     * @return
     */
    protected Connection getConnection(String fullConnectionStr){
        boolean isSuccess = this.injectClassLoader();
        if(!isSuccess){
            throw new DataBaseMetaError("加载SPI动态数据源失败！请检查是否存在第三方数据库驱动类在classpath中");
        }
        try {
            return DriverManager.getConnection(fullConnectionStr);
        } catch (SQLException e) {
            throw new DataBaseMetaError("连接数据库出现异常",e);
        }
    }

    /**
     *
     * @param user
     * @param password
     * @param url
     * @return
     */
    protected Connection getConnection(String user,String password,String url){
        boolean isSuccess = this.injectClassLoader();
        if(!isSuccess){
            throw new DataBaseMetaError("加载SPI动态数据源失败！请检查是否存在第三方数据库驱动类在classpath中");
        }
        try {
            return DriverManager.getConnection(url,user,password);
        } catch (SQLException e) {
            throw new DataBaseMetaError("连接数据库出现异常",e);
        }
    }

}
